# -*- encoding: utf-8 -*-
from decimal import Decimal
from datetime import datetime

from .ws_client import get_ws_client
from . import dbhelper


def test_job_func(a=0, b=0, ws_cfg={}):
    v = str(a + b)
    print('job print: {0}'.format(v))
    print(ws_cfg)
    if bool(ws_cfg):
        ws_client = get_ws_client(ws_cfg)
        print(ws_client)
        ws_client.emit(
            'send_log',
            'hello world from task',
            path=ws_cfg['namespace']
        )
    return 'job-result'

def execute_write(sql, params={}, ws_cfg={}):
    engine = dbhelper.get_sqlalchemy_engine()
    connection = engine.connect()
    result = connection.execution_options(autocommit=True).execute(sql, **params)
    affect = result.rowcount
    connection.close()
    engine.dispose()

    ws_client = get_ws_client(ws_cfg)
    ws_client.emit(
        'send_log',
        {
            'affect': affect
        },
        path=ws_cfg['namespace']
    )
    ws_client.disconnect()

def execute_read(sql, params={}, ws_cfg={}):
    engine = dbhelper.get_sqlalchemy_engine()
    connection = engine.connect()
    # http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.ResultProxy
    result = connection.execution_options(autocommit=True).execute(sql, **params)
    data = []
    columns = {}
    if bool(result) and result.returns_rows:
        columns = result.keys()
        for row in result:
            row_item = dict(row.items())
            item = {}
            for k in row_item:
                v = row_item[k]
                if isinstance(v, Decimal):
                    v = float(v)
                elif isinstance(v, datetime):
                    v = v.strftime('%Y-%d-%m %H:%M:%S')
                item[k] = v
            data.append(item)
    else:
        print('nothing')
    connection.close()
    engine.dispose()

    ws_client = get_ws_client(ws_cfg)
    ws_client.emit(
        'send_log',
        {
            'columns': columns,
            'data': data
        },
        path=ws_cfg['namespace']
    )
    ws_client.disconnect()